<template>
<div>
    <div style="display:flex;">
        <div style="flex:16;background-color: #fafafa;height: 92.7vh;"  v-loading="isPay" element-loading-text="支付中...">
            <el-row style="justify-content: center;align-items:center;height: 10vh;padding-left: 2%;padding-right: 3%">
                <el-col :span="8">
                    <el-text style="font-size: 30px">收银</el-text>
                </el-col>
                <el-col :span="8" style="text-align: right;padding-right: 2%">
                    <el-button :icon="Plus" size="large" @click="handleShowAddTemp">
                        <el-text>临时商品</el-text>
                    </el-button>
                </el-col>
                <el-col :span="8">
                    <el-autocomplete
                        v-model="searchValue"
                        placeholder="输入名称或条码"
                        :prefix-icon="Search"
                        style="max-width: 20vw"
                        size="large"
                        :trigger-on-focus="false"
                        :fetch-suggestions="querySearch"
                        clearable
                        @select="handleSearchSelect"
                    >
                        <template #default="{ item }">
                            <div >
                              <el-text>{{ item.goodsName }}</el-text>
                            </div>
                            <div >
                              <el-text size="small">{{ item.code }}</el-text>
                            </div>
                        </template>
                    </el-autocomplete>
                </el-col>
            </el-row>
            <el-row>
                <el-table :data="payBo.detailObject"
                          height="67vh"
                          style="width: 100%;"
                          :header-cell-style="{ 'text-align': 'center' }"
                          :cell-style="{ textAlign: 'center' }"
                >
                    <el-table-column prop="goodsName" label="商品名"  />
                    <el-table-column prop="price" label="单价" />
                    <el-table-column label="数量" >
                        <template #default="scope">
                            <el-input-number v-model="scope.row.num" :min="1" style="width: 65%"/>
                        </template>
                    </el-table-column>
                    <el-table-column label="金额">
                        <template #default="scope">
                            <el-text>{{scope.row.num * scope.row.price}}</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column >
                        <template #default="scope">
                            <el-button
                                link
                                type="danger"
                                size="small"
                                :icon="Close"
                                @click.prevent="deleteRow(scope.$index)"/>

                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
            <el-row justify="end">
                <div style="text-align: center;margin: 10px 20px 10px 10px">
                    <div>
                        <el-text size="large">共{{getTotalAndNum()}}件，总计{{payBo.total}}元</el-text>
                    </div>
                    <div>
                        <el-text size="small">实际优惠以结算页面为准</el-text>
                    </div>
                </div>
            </el-row>
            <el-row >
                <el-col :span="12" style="padding-left: 20px">
                  <el-badge v-if="payBo.detailObject.length===0" :value="payRegisterDate.length" :hidden="payRegisterDate.length===0">
                    <el-button type="info" size="large" round @click="showPayRegister">取单</el-button>
                  </el-badge>
                  <div v-else>
                    <el-button  type="info" size="large" round @click="inPayRegister">挂单</el-button>
                    <el-button  type="danger" size="large" round @click="payBo.detailObject=[]" style="margin-left: 3%">
                      清空
                    </el-button>
                  </div>

                </el-col>
                <el-col :span="12" style="padding-right: 20px">
                    <div style="text-align: right">
                        <el-button v-if="payBo.detailObject.length!==0" type="warning" size="large" round style="width: 100px" @click="pay">收款</el-button>
                    </div>
                </el-col>
            </el-row>
        </div>
        <div style="flex:8;background-color: #014164;height: 92.7vh;">
            <div>
                <div style="min-width: 100%;margin: 10px 10px 10px 10px;text-align: center">
                    <div style="margin-bottom: 2%">
                        <el-text style="color:#eaeaea;" size="large">
                            上一订单
                        </el-text>
                    </div>
                    <el-scrollbar style="max-height: 30vh;">
                        <div style="display: flex" v-for="item in lastOrder.detailObject" :key="item">
                            <div style="flex: 12">
                                <el-text style="color:#eaeaea;" size="large">
                                    {{item.goodsName}}
                                </el-text>
                            </div>
                            <div style="flex: 12">
                                <el-text style="color:#eaeaea;" size="large">
                                    {{item.num}}
                                </el-text>
                            </div>
                        </div>
                    </el-scrollbar>
                    <div style="border-bottom: 1px solid #eaeaea;padding-bottom: 5px">
                        <el-text style="color:#eaeaea;" size="large">共{{getTotalAndNum2(lastOrder.detailObject).num}}件，总计{{lastOrder.total}}元</el-text>
                    </div>
                </div>
            </div>
            <div style="margin: 10px 10px 10px 10px">
                <div v-if="handleOffers().global!==''" style="margin-bottom: 10px">
                    <el-text style="color:#eaeaea;" size="large">
                        全场活动：
                    </el-text>
                    <el-text style="color:#eaeaea;" size="large">
                        {{handleOffers().global}}
                    </el-text>
                </div>
                <div  v-if="handleOffers().byCode.length!==0">
                    <el-text style="color:#eaeaea;" size="large">
                        商品活动：
                    </el-text>
                    <div v-for="item in handleOffers().byCode" :key="item">
                        <el-text style="color:#eaeaea;" size="large">
                            {{item.goodsName}}<br/>
                        </el-text>
                        <el-text style="color:#eaeaea;" size="large">
                            {{item.offers}}
                        </el-text>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

    <el-dialog v-model="showAddTemp" title="临时商品" width="20%" center>
        <el-form>
            <el-form-item label="价格" label-width="100px" >
                <el-row justify="space-evenly" style="justify-content: center;align-items:center;">
                    <el-col :span="12">
                        <el-input v-model="tempPrice" type="number" style="max-width: 100px" />
                    </el-col>
                    <el-col :span="12">
                        <el-button  style="margin-left: 5%;" @click="addTemp"><el-text size="small">添加</el-text></el-button>
                    </el-col>
                </el-row>
            </el-form-item>
        </el-form>
    </el-dialog>
  <PayRegister  ref="payRegister" @confirmPayRegister="confirmPayRegister"/>
  <HandlePay ref="handlePay" @confirmHandlePay="confirmHandlePay"/>
</template>

<script setup>
import {
    Plus, Search,Close
} from '@element-plus/icons-vue'
import {onMounted, ref} from "vue";
import request from "@/utils/request";
import {store} from "@/store";
import PayRegister from "@/components/pay/PayRegister";
import {ElMessage} from "element-plus";
import HandlePay from "@/components/pay/HandlePay";

const searchValue=ref("")
const showAddTemp=ref(false)
let tempPrice=ref(1)
const payBo=ref({
    storeId:store.getLocalCurrentStoreMain().storeId,
    payment:"现金收款",
    detailObject:[],
    total:0.0,
    attach:"",
    cashier:store.getLocalEmployeeMain()==null?store.getLocalUserMain().id:store.getLocalEmployeeMain().name
})
const payRegisterDate=ref([])
const payRegister=ref()
const handlePay=ref()
let isPay=ref(false)
const offers=ref([])
const lastOrder=ref({})
onMounted(()=>{
    setTimeout(()=>{
        if (store.goodsStoreInfoList.length===0){
            request.get("/goods/get/goodsCodeList/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
                store.goodsStoreInfoList=[]
                for (let i in res.data){
                    store.goodsStoreInfoList.push(store.getLocalStorage(res.data[i]))
                }
            })
        }
        request.get("/store/get/StoreOffersListRuing/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
          offers.value=res.data
        })
        request.get("/pay/get/lastOrderByDone/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
            lastOrder.value=res.data
        })
    },1000)
  request.get("/pay/get/payRegister/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
    payRegisterDate.value=res.data
  })
  watchScanGun()
})

const deleteRow = (index) => {
    payBo.value.detailObject.splice(index, 1)
}

const onAddItem = (goodsInfo) => {


    if (payBo.value.detailObject.filter((p)=>{
        return p.code.indexOf(goodsInfo.code) !==-1
    }).length!==0){
        payBo.value.detailObject.filter((p)=>{
            payBo.value.detailObject[p.code.indexOf(goodsInfo.code)].num+=1
        })
    }else {

        payBo.value.detailObject.push({
            code:goodsInfo.code,
            goodsName:goodsInfo.goodsName,
            storeId:store.getLocalCurrentStoreMain().storeId,
            cost:goodsInfo.cost,
            price:goodsInfo.price,
            warn:3,
            state:0,
            num:1,
        })
    }
}
const handleShowAddTemp = (evt) => {
  evt.target.blur();
  if(evt.target.nodeName === "SPAN"){
    evt.target.parentNode.blur();
  }
  showAddTemp.value=true
}
const addTemp=()=>{
    const code=Math.ceil(Date.now()/1000)+""
    onAddItem({
        code:code,
        goodsName:"临时商品"+code,
        storeId:store.getLocalCurrentStoreMain().storeId,
        cost:0.0,
        price:tempPrice.value,
    })
    showAddTemp.value=false
    tempPrice.value=1
}

function getTotalAndNum(){
    let num=0
    let total=0.0
    for (let i in payBo.value.detailObject){
        num+=payBo.value.detailObject[i].num
        total+=payBo.value.detailObject[i].num*payBo.value.detailObject[i].price
    }
    payBo.value.total=total
    return num
}

function getTotalAndNum2(data){
    let num=0
    let total=0.0
    for (let i in data){
        num+=data[i].num
        total+=data[i].num*data[i].price
    }

    return {
        num,
        total
    }
}


const querySearch = (queryString, cb) => {

    const results = queryString
        ? store.goodsStoreInfoList.filter((p)=>{
            return p.goodsName.indexOf(queryString) !==-1 || p.code.indexOf(queryString) !==-1
        })
        : store.goodsStoreInfoList
    // call callback function to return suggestions
    cb(results)
}

const handleSearchSelect = (item) => {
  onAddItem(item)
}

const inPayRegister = () => {
  let detailObjectTemp=payBo.value.detailObject
  for (let item in detailObjectTemp){
    detailObjectTemp[item].total=detailObjectTemp[item].num * detailObjectTemp[item].price
  }
  const payRegisterTemp={
    storeId:store.getLocalCurrentStoreMain().storeId,
    detailObject:detailObjectTemp
  }
  request.post("/pay/add/payRegister",payRegisterTemp).then(res=>{
    request.get("/pay/get/payRegister/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
      payRegisterDate.value=res.data
      payBo.value.detailObject=[]
    })
  })
}

const showPayRegister = () => {
  payRegister.value.show(payRegisterDate.value)
}

const confirmPayRegister = (payRegister) => {
  payBo.value.detailObject=payRegister
  payRegisterDate.value.splice(payRegisterDate.value.indexOf(payRegister),1)
}

const watchScanGun = () => {
  // 监听按键
  let code = '';
  let lastTime, nextTime; // 上次时间、最新时间
  let lastCode, nextCode; // 上次按键、最新按键
  document.onkeypress = (e) => {
    // 获取按键
    if (window.event) { // IE
      nextCode = e.keyCode
    } else if (e.which) { // Netscape/Firefox/Opera
      nextCode = e.which
    }
    // 如果触发了回车事件(扫码结束时间)
    if (nextCode === 13) {

      if (code.length < 3) return // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有

      codeFind(code) // 获取到扫码枪输入的内容，做别的操作

      code = ''
      lastCode = ''
      lastTime = ''
      return
    }
    nextTime = new Date().getTime() // 记录最新时间
    if (!lastTime && !lastCode) { // 如果上次时间和上次按键为空
      code += e.key // 执行叠加操作
    }
    // 如果有上次时间及上次按键
    if (lastCode && lastTime && nextTime - lastTime > 30) { // 当扫码前有keypress事件时,防止首字缺失
      code = e.key
    } else if (lastCode && lastTime) {
      code += e.key
    }
    lastCode = nextCode
    lastTime = nextTime
  }
}
const codeFind = (code) => {
  showAddTemp.value=false
  if (code.length===13){
    if (store.getLocalStorage(code)==null){
      ElMessage({
        message: '查无此商品',
        type: 'warning',
      })
    }else
      onAddItem(store.getLocalStorage(code))
  } else if (code.length===18){
    if (payBo.value.detailObject.length!==0){
      isPay.value=true
      payBo.value.authCode=code
      request.post("/pay/placeOrder/authCode",payBo.value).then(res=>{
        showAddTemp.value=false
        if (res.data==="SUCCESS"){
          showAddTemp.value=false
          payBo.value.detailObject=[]
          isPay.value=false
          ElMessage({
            message: '支付成功',
            type: 'success',
          })
          setTimeout(()=>{
            request.get("/pay/get/lastOrderByDone/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
              lastOrder.value=res.data
            })
          },1000)
        }else {
          showAddTemp.value=false
          isPay.value=false
          ElMessage({
            message: '支付失败，请重试',
            type: 'success',
          })
        }
      })
    }
  }
  showAddTemp.value=false
}
const pay = () => {
  handlePay.value.show(payBo.value)
}
const confirmHandlePay = () => {
  payBo.value.detailObject=[]
  setTimeout(()=>{
    request.get("/pay/get/lastOrderByDone/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
      lastOrder.value=res.data
    })
  },1000)
}
const handleOffers = () => {
  let global=""
    let byCode=[]
    for (let item in offers.value){
        if (offers.value[item].code==="global"){
            let temp=offers.value[item].attachObj
            if(temp.attach.indexOf("满减")!==-1){
                global=global+" "+"满"+temp.fullDecr+"减"+temp.fullDecrCost
            }
            if(temp.attach.indexOf("打折")!==-1){
                global=global+" 全场 "+temp.discount*10+" 折"
            }
        }else {
            let temp1=offers.value[item].attachObj
            let temp2={}
            temp2.goodsName=store.getLocalStorage(offers.value[item].code).goodsName
            temp2.offers=""
            if(temp1.attach.indexOf("满减")!==-1){
                temp2.offers=temp2.offers+" "+"满"+temp1.fullDecr+"减"+temp1.fullDecrCost
            }
            if(temp1.attach.indexOf("打折")!==-1){
                temp2.offers=temp2.offers+"  打 "+temp1.discount*10+" 折"
            }
            byCode.push(temp2)
        }
    }

    return{
        global,
        byCode
    }
}
</script>

<style scoped>

</style>